<template>
  <div>
    <el-row>
      <el-col>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rulsform" label-width="auto">
          <el-form-item label="账号" prop="username">
            <el-input v-model="ruleForm.username" :prefix-icon="User" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password" :prefix-icon="Lock" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="submitForm(ruleFormRef)"> Submit </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
let { userLogin } = useUserStore()
const $router = useRouter()
const ruleFormRef = ref<FormInstance>()
let loading = ref(false)
const ruleForm = reactive({
  username: '',
  password: '',
})
interface RuleForm {}
const rulsform = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 5, max: 10, message: '账号至少5位', trigger: 'blur' },
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate()
  try {
    loading.value = true
    await userLogin(ruleForm)
    $router.push('/')
    ElNotification({
      type: 'success',
      message: '登录成功',
    })
    loading.value = false
  } catch (error) {
    loading.value = false
    ElNotification({
      title: 'error',
      message: (error as Error).message,
    })
  }
}
</script>

<style scoped></style>
